package memorphic.slide.plugin.wizards;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.internal.ide.misc.ContainerContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;

/**
 * The "New" wizard page allows setting the container for the new file as well
 * as the file name. The page will only accept file name without the extension
 * OR with the extension that matches the expected one (mpe).
 */

public class NewFeatureWizardPage extends WizardPage {
	
	private TreeViewer projectSrc;
	
	private Text featureName;
	
	private Text featurePackage;

	private Text contextClassName;

	private Text featureID;

	private Text controllerClassName;
	
	private Text stateClassName;
	
	private Button useDefault;
	
	private IContainer selectedContainer;
	
	private String projectDirectory;
	
	private ISelection selection;
	
	/**
	 * Constructor for NewFeatureWizardPage.
	 * 
	 * @param pageName
	 */
	public NewFeatureWizardPage(ISelection selection) {
		super("wizardPage");
		setTitle("Multi-page Editor File");
		setDescription("This wizard creates a new file with *.mpe extension that can be opened by a multi-page editor.");
		this.selection = selection;
	}

	/**
	 * @see IDialogPage#createControl(Composite)
	 */
	public void createControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 2;
		layout.verticalSpacing = 9;

		Label label = new Label(container, SWT.NULL);
		label.setText("&Project source:");


		projectSrc = new TreeViewer(container);
		GridData gd = new GridData(GridData.FILL_BOTH);
		projectSrc.getTree().setLayoutData(gd);
		ContainerContentProvider cp = new ContainerContentProvider();
		cp.showClosedProjects(false);
		projectSrc.setContentProvider(cp);
		projectSrc.setLabelProvider(WorkbenchLabelProvider
				.getDecoratingWorkbenchLabelProvider());
		projectSrc.setComparator(new ViewerComparator());
		projectSrc.setUseHashlookup(true);
		projectSrc.setInput(ResourcesPlugin.getWorkspace());
		
		projectSrc.setSelection(selection);
		
		projectSrc.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(SelectionChangedEvent event) {
				IStructuredSelection selection = (IStructuredSelection) event
						.getSelection();
				containerSelectionChanged((IContainer) selection
						.getFirstElement()); // allow null
				dialogChanged();
			}
		});
		projectSrc.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				ISelection selection = event.getSelection();
				if (selection instanceof IStructuredSelection) {
					Object item = ((IStructuredSelection) selection)
							.getFirstElement();
					if (item == null) {
						return;
					}
					if (projectSrc.getExpandedState(item)) {
						projectSrc.collapseToLevel(item, 1);
					} else {
						projectSrc.expandToLevel(item, 1);
					}
				}
			}
		});
		containerSelectionChanged((IContainer) ((IStructuredSelection)selection).getFirstElement());
		
		label = new Label(container, SWT.NULL);
		label.setText("&Feature name:");

		featureName = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		featureName.setLayoutData(gd);
		featureName.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});

		label = new Label(container, SWT.NULL);
		label.setText("&Use Default:");

		useDefault = new Button(container, SWT.CHECK);
		useDefault.setSelection(true);
		useDefault.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				toggleUseDefaults();
				dialogChanged();
			}
		});
		
		label = new Label(container, SWT.NULL);
		label.setText("&Feature package:");
		
		featurePackage = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		featurePackage.setLayoutData(gd);
		featurePackage.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});
/*
		Button button = new Button(container, SWT.PUSH);
		button.setText("Browse...");
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				handleBrowse();
			}
		});
 */

		label = new Label(container, SWT.NULL);
		label.setText("&Feature ID:");

		featureID = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		featureID.setLayoutData(gd);
		featureID.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});
		
		label = new Label(container, SWT.NULL);
		label.setText("&Context class:");
		
		contextClassName = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		contextClassName.setLayoutData(gd);
		contextClassName.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});

		label = new Label(container, SWT.NULL);
		label.setText("&Controller class:");

		controllerClassName = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		controllerClassName.setLayoutData(gd);
		controllerClassName.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});

		label = new Label(container, SWT.NULL);
		label.setText("&State class:");

		stateClassName = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		stateClassName.setLayoutData(gd);
		stateClassName.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});
		
		initialize();
		toggleUseDefaults();
		dialogChanged();
		setControl(container);
	}
	

	/**
	 * Tests if the current workbench selection is a suitable container to use.
	 */

	private void initialize() {
		if (selection != null && selection.isEmpty() == false
				&& selection instanceof IStructuredSelection) {
			/*IStructuredSelection ssel = (IStructuredSelection) selection;
			if (ssel.size() > 1)
				return;
			Object obj = ssel.getFirstElement();
			if (obj instanceof IResource) {
				IContainer container;
				if (obj instanceof IContainer)
					container = (IContainer) obj;
				else
					container = ((IResource) obj).getParent();
				//containerText.setText(container.getFullPath().toString());
			}*/
		}
		//fileText.setText("new_file.mpe");
		
	}

	/**
	 * The container selection has changed in the tree view. Update the
	 * container name field value and notify all listeners.
	 * 
	 * @param container
	 *            The container that changed
	 */
	public void containerSelectionChanged(IContainer container) {
		selectedContainer = container;
		
		
		
		if (selectedContainer != null)
		{
			IProject project = selectedContainer.getProject();
			IProject[] projs = ResourcesPlugin.getWorkspace().getRoot().getProjects();
			for (int i = 0; i < projs.length; i++)
			{
				IProject proj = projs[i];
				if (proj  == project)
				{
					projectDirectory = proj.getLocation().toOSString();
				}
			}
		}
		
		
//		if (allowNewContainerName) {
//			if (container == null) {
//				containerNameField.setText("");//$NON-NLS-1$
//			} else {
//				String text = TextProcessor.process(container.getFullPath()
//						.makeRelative().toString());
//				containerNameField.setText(text);
//				containerNameField.setToolTipText(text);
//			}
//		}
//
//		// fire an event so the parent can update its controls
//		if (listener != null) {
//			Event changeEvent = new Event();
//			changeEvent.type = SWT.Selection;
//			changeEvent.widget = this;
//			listener.handleEvent(changeEvent);
//		}
//		
	}
	
	private void toggleUseDefaults() {
		featurePackage.setEnabled(!useDefault.getSelection());
		featureID.setEnabled(!useDefault.getSelection());
		contextClassName.setEnabled(!useDefault.getSelection());
		controllerClassName.setEnabled(!useDefault.getSelection());
		stateClassName.setEnabled(!useDefault.getSelection());
	}
	
	/**
	 * Ensures that both text fields are set.
	 */

	private void dialogChanged() {
		
		if (selectedContainer == null)
		{
			updateStatus("A project must be specified must be specified");
			return;
		}
		if (getFeatureName().length() == 0)
		{
			updateStatus("Feature name must be specified");
			return;
		}
		if (getFeaturePackage().length() == 0) {
			updateStatus("Feature package must be specified");
			return;
		}
		if (getFeatureID().length() == 0)
		{
			updateStatus("Feature ID must be specified");
			return;
		}
		if (getContextClassName().length() == 0) {
			updateStatus("Context class name must be specified");
			return;
		}
		if (getControllerClassName().length() == 0) {
			updateStatus("Controller class name must be specified");
			return;
		}
		if (getStateClassName().length() == 0) {
			updateStatus("State class name must be specified");
		}
		/*
		if (className.replace('\\', '/').indexOf('/', 1) > 0) {
			updateStatus("File name must be valid");
			return;
		}
		*/
		/*
		int dotLoc = fileName.lastIndexOf('.');
		if (dotLoc != -1) {
			String ext = fileName.substring(dotLoc + 1);
			if (ext.equalsIgnoreCase("mpe") == false) {
				updateStatus("File extension must be \"mpe\"");
				return;
			}
		}
		*/
		updateStatus(null);
	}

	private void updateStatus(String message) {
		setErrorMessage(message);
		setPageComplete(message == null);
	}

	
	public String getProjectDirectory() {
		return projectDirectory;
	}
	
	public IProject getProject() {
		return selectedContainer.getProject();
	}
	
	public String getProjectSourcePath() {
		String projectSourcePath = selectedContainer.getProjectRelativePath().toOSString();
		return projectSourcePath;
	}
	
	public String getFeatureName() {
		return featureName.getText();
	}
	
	public String getFeaturePackage() {
		return featurePackage.getText();
	}
	
	public String getFeatureID() {
		return featureID.getText();
	}

	public String getContextClassName() {
		return contextClassName.getText();
	}
	
	public String getControllerClassName() {
		return controllerClassName.getText();
	}
	
	public String getStateClassName() {
		return stateClassName.getText();
	}
	
}